package com.tool_stdy.utils.guava.ratelimit;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.RateLimiter;

/**
 * Created by yan_li on 2017/4/28.
 */
public class RateLimitTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        testRateLimiter();
    }

    /**
     * RateLimiter类似于JDK的信号量Semphore，他用来限制对资源并发访问的线程数
     */
    public static void testRateLimiter() {
        ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));

        RateLimiter limiter = RateLimiter.create(3.0); // 每秒不超过4个任务被提交

        for (int i = 0; i < 10; i++) {
            limiter.acquire(); // 请求RateLimiter, 超过permits会被阻塞
            final ListenableFuture<Integer> listenableFuture = executorService.submit(new Task("is " + i + "--" + limiter.getRate()));

        }
    }
}

class Task implements Callable<Integer> {
    String str;

    public Task(String str) {
        this.str = str;
    }

    @Override
    public Integer call() throws Exception {
        System.out.println(System.currentTimeMillis() / 1000 + "---" + Thread.currentThread().getName() + "-call execute.." + str);
        TimeUnit.SECONDS.sleep(10);
        return 7;
    }
}
